﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Liger.Common;
using Liger.Data;
using Liger.Common.Extensions;
using EasyFMS.Model;
using EasyFMS.Common; 
using Liger.Data.Linq;
using System.Text.RegularExpressions;

namespace EasyFMS.Service
{
    public class SystemService
    {
        public static DbContext DB = DbHelper.Db;

        /// <summary>
        /// 判断指定用户是否系统管理员
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static bool IsAdministrator(int UserID)
        {
            return DB.From<tUser>().Where(tUser._.UserID == UserID && tUser._.IsSystem == true).Count() > 0;
        }

        /// <summary>
        /// 判断当前用户是否是系统管理员
        /// </summary>
        /// <returns></returns>
        public static bool IsAdministrator()
        {
            return IsAdministrator(SysContext.CurrentUserID);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        public static bool UserLogin(string username, string password)
        {
            var loginSuccess = DB.From<tUser>().Where(tUser._.UserCode == username && tUser._.Password == password).Any();
            if (loginSuccess)
            {
                var user = DB.From<tUser>().Where(tUser._.UserCode == username && tUser._.Password == password).ToFirst();
                var roles = DB.From<vUserDepartment>().Where(vUserDepartment._.UserID == user.UserID).ToList();
                SysContext.CurrentUserID = user.UserID.ToInt();
                SysContext.CurrentDeptID = user.UID;
                SysContext.CurrentUserTitle = user.UserName;
                SysContext.CurrentRoleID = string.Join(",", roles.Select(c => c.DeparemntCode.ToString()).ToArray());
                SysContext.CurrentRoleName = string.Join(",", roles.Select(c => c.DepartmentName.ToString()).ToArray());
                LogManager.WriteLog("USER", user.UserName + " 登陆系统");
            }
            return loginSuccess;
        }

        /// <summary>
        /// 获取指定用户有权限的菜单列表
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static List<tModuleTree> GetUserMenus(int UserID)
        {
            //如果没有启用权限控制，或者是管理员，直接获取全部菜单
            if (IsAdministrator(UserID))
                return DB.From<tModuleTree>().ToList();
            var ds = DB.ExecuteDataSet(GetUserMenusCommandText(UserID));
            if (ds == null || ds.Tables.Count == 0)
                return new List<tModuleTree>();
            return DbEntityHelper.DataTableToEntities<tModuleTree>(ds.Tables[0]);
        }

        /// <summary>
        /// 查询某个用户菜单模块的SQL
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        private static string GetUserMenusCommandText(int UserID)
        {
            string cmdText = @" SELECT a.UID AS UserID,a.USERCODE,a.USERNAME,c.GroupCode, c.GroupName,e.ModuleAlias,e.IsFolder,e.ParentID,e.Seq,e.ModuleTreeUID FROM dbo.tUser a " +
                        "INNER JOIN dbo.tRightGroupUser b ON a.UserCode = b.UserCode INNER JOIN dbo.tRightGroup c ON b.GroupCode = c.GroupCode " +
                        "INNER JOIN dbo.tRightGroupModule d ON c.GroupCode = d.GroupCode INNER JOIN dbo.tModuleTree e ON d.ModuleID = e.ModuleID " +
                        " WHERE d.ModuleVerb = '打开' AND a.UID = {0} ORDER BY e.ParentID " +
                        "UNION ALL SELECT a.UID AS UserID,a.USERCODE,a.USERNAME,c.GroupCode, c.GroupName,e.ModuleAlias,e.IsFolder,e.ParentID,e.Seq,e.ModuleTreeUID " +
                        "FROM dbo.tUser a INNER JOIN dbo.tRightGroupUser b ON a.UserCode = b.UserCode INNER JOIN dbo.tRightGroup c ON b.GroupCode = c.GroupCode " +
                        "CROSS JOIN dbo.tModuleTree E WHERE E.IsFolder = 1 AND a.UID = {1} ORDER BY ParentID,Seq ";
            return cmdText.FormatWith(UserID,UserID);
        }

        /// <summary>
        /// 获取指定用户有权限的菜单列表(JSON Tree格式)
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public static string GetUserMenusTreeJSON(int UserID)
        {
            return JSONHelper.GetArrayJSON(GetUserMenusCommandText(UserID), "ModuleTreeUID", "ParentID");
        }

        /// <summary>
        /// 判断某按钮是否有权限
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Roles"></param>
        /// <returns></returns>
        public static bool HasButtonPermission(int UserID, int BtnID)
        {
            //return DB.ExecuteScalar(queryPermit).ToInt() > 0 && DB.ExecuteScalar(queryForbid).ToInt() == 0;
            return true;
        }

    }
}